package com.weilus.service;

import com.weilus.entity.TT;
import com.weilus.dao.TTMapper;
import com.weilus.dao.TTRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.core.DatabaseClient;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TestService {

    @Autowired
    TTRepository repository;
    @Autowired
    TTMapper ttMapper;
    @Autowired
    DatabaseClient databaseClient;

    public Mono<Page<TT>> page(int page, int size){
        log.debug("分页查询......");
        Pageable pageable = PageRequest.of(page - 1,size, Sort.by("createTime").descending());
        return repository.count()
                .zipWhen(total -> {
                            if(total > 0) return repository.findAllBy(pageable).collect(Collectors.toList());
                            else return Mono.just(Collections.EMPTY_LIST);
                        },
                        (total, list)->PageableExecutionUtils.getPage(list,pageable,()->total));
    }

    public Mono<TT> findById(Long id){
        log.debug("按ID查询......");
        return repository.findById(id);
    }

//    public Flux<TT> query(){
//        String sql = "SELECT id,name,age,foo,create_time,update_time FROM t_t";
//        return databaseClient.execute(sql).as(TT.class).fetch().all();
//    }

    public Mono<TT> add(TT t) {
        log.debug("新增......");
        t.setCreateTime(LocalDateTime.now());
        return repository.save(t);
    }

    @Transactional
    public Mono<TT> edit(TT t){
//        ttMapper.updateByCriteriaSelective(t, Criteria
//                                                   .where("name").is("")
//                                                   .and("age").is(55));
        log.debug("修改非空字段......");
        return  ttMapper.updateByPrimaryKeySelective(t)
                .then()
                .then(Mono.defer(()->{
                    if(t.getCreateTime() != null)return Mono.error(new RuntimeException("不能改创建时间"));
                    else return Mono.empty();
                }))
                .then(repository.findById(t.getId()));
    }


}
